#!/usr/bin/python3
import sys
import os
import shutil

def make_dir(home_dir, num_100, num_10):
    """Create necessary directory structure"""
    # Create base directory structure
    dir_path = os.path.join(home_dir, "a")
    if not os.path.exists(dir_path):
        os.makedirs(dir_path, mode=0o777)
    
    dir_path = os.path.join(dir_path, "0")
    if not os.path.exists(dir_path):
        os.makedirs(dir_path, mode=0o777)
    
    dir_path = os.path.join(dir_path, "0")
    if not os.path.exists(dir_path):
        os.makedirs(dir_path, mode=0o777)
    
    # Create numbered directories
    dir_path = os.path.join(home_dir, "a", str(num_100))
    if not os.path.exists(dir_path):
        os.makedirs(dir_path, mode=0o777)
    
    dir_path = os.path.join(dir_path, str(num_10))
    if not os.path.exists(dir_path):
        os.makedirs(dir_path, mode=0o777)

def file_write(arc_data, index, num_100, num_10, num_1, home_dir, write_count, pm_version):
    """Write file and update counters"""
    enum = arc_data[index]
    tree = f"a/{num_100}/{num_10}/{num_1}"
    file_num = index + 1
    
    # Find the filename
    while not arc_data[file_num].strip():
        file_num += 1
        if file_num >= len(arc_data):
            print("Error: Not Found FileName")
            sys.exit(1)
    
    file = arc_data[file_num].strip().replace('"', '')
    if file.startswith('#'):
        print(f"Error: Not Found FileName {file}")
        sys.exit(1)
    
    # Write to file_tree.inc
    if write_count > 0:
        print(" \\", file=arc_tree)
    
    # Check for NOSHORT flag
    if file_num < len(arc_data) - 1 and arc_data[file_num + 1].strip() == "NOSHORT":
        print(f"\t{file}", end='', file=arc_tree)
        return num_100, num_10, num_1, write_count + 1
    
    print(f"\t{tree}", end='', file=arc_tree)
    
    # Update counters
    num_1 += 1
    flag = False
    if num_1 > 9:
        num_1 = 0
        num_10 += 1
        flag = True
        if num_10 > 9:
            num_10 = 0
            num_100 += 1
            if num_100 > 9:
                print("Error: File Max Over")
                sys.exit(1)
    
    if flag:
        make_dir(home_dir, num_100, num_10)
    
    # Copy file
    src_file = os.path.join(home_dir, file)
    dst_file = os.path.join(home_dir, tree)

    
    return num_100, num_10, num_1, write_count + 1

def main():
    if len(sys.argv) < 4:
        print("error: python script.py read_file pm_version home_dir")
        sys.exit(1)
    
    # Read input file
    try:
        with open(sys.argv[1], 'r') as f:
            data = f.readlines()
    except Exception as e:
        print(f"Error reading file {sys.argv[1]}: {e}")
        sys.exit(1)
    
    # Initialize variables
    global arc_tree
    arc_tree = open("file_tree.inc", "w")
    print("FILE_TREE2=", end='', file=arc_tree)
    
    num_1 = 0
    num_10 = 0
    num_100 = 0
    write_count = 0
    
    # Create initial directory structure
    make_dir(sys.argv[3], num_100, num_10)
    
    # Process each line
    for line in data:
        arc_data = line.split()
        if not arc_data:
            continue
        
        for i, item in enumerate(arc_data):
            if not item:
                continue
            
            if item.startswith('$'):
                version = item.replace('$', '')
                if version == sys.argv[2]:
                    num_100, num_10, num_1, write_count = file_write(
                        arc_data, i+1, num_100, num_10, num_1, 
                        sys.argv[3], write_count, sys.argv[2]
                    )
                break
            elif item.startswith('#'):
                break
            else:
                num_100, num_10, num_1, write_count = file_write(
                    arc_data, i, num_100, num_10, num_1,
                    sys.argv[3], write_count, sys.argv[2]
                )
                break
    
    arc_tree.close()

if __name__ == "__main__":
    main()